package cn.xiqi.cms.hibernate.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xiqi.cms.hibernate.DAO.DataDAO;
import cn.xiqi.cms.hibernate.beans.Metadata;

public class DataServiceImpl implements DataService {
	private DataDAO dao;

	@Override
	public Metadata getByID(int id) {
		Metadata record;
		Map<String, Object> values = new HashMap<>();
		
		values.put("type", "id");
		values.put("id", id);
		record = dao.select(values).get(0);
		return record;
	}

	@Override
	public List<String> getCate() {
		List<Metadata> records;
		Map<String, Object> values = new HashMap<>();
		List<String> cates = new ArrayList<>();
		String cate;
		
		values.put("type", "all");
		records = dao.select(values);
		for(Metadata record:records) {
			cate = record.getCate();
			if(!cates.contains(cate))
				cates.add(cate);
		}
		return cates;
	}

	@Override
	public List<Metadata> getByCate(String cate) {
		List<Metadata> records;
		Map<String, Object> values = new HashMap<>();
		
		values.put("type", "cate");
		values.put("cate", cate);
		records = dao.select(values);
		return records;
	}

	@Override
	public int addCate(String cate) {
		Metadata record = new Metadata(cate);
		int id = dao.insert(record);
		return id;
	}

	@Override
	public int addValue(String cate, String key, int value) {
		List<Metadata> records;
		Metadata record;
		int id;
		
		records = getByCate(cate);
		record = records.get(0);
		if(record.getKey()==null) {
			record.setKey(key);
			record.setValue(value);
			dao.update(record);
			id = record.getDataID();
		}
		else {
			record = new Metadata(cate, key, value);
			id = dao.insert(record);
		}
		return id;
	}

	@Override
	public void setDao(DataDAO dao) {
		this.dao = dao;
	}
	
	@Override
	public boolean update(Metadata record){
		boolean b = dao.update(record);
		return b;
	}

	@Override
	public boolean delete(Metadata record) {
		boolean b = dao.delete(record);
		return b;
	}

}
